/*
 * lib2Desa - Another 2D game library in C++
 * Copyright (C) 2009 Erivaldo Xavier de Lima Filho
 *
 * This program is free software and is distributed under GNU General Public License version 3. You can modify and/or redistribute
 * it under the terms of GPL version 3 or posterior version. This program comes with NO WARRANTY, for more details, see LICENSE,
 * or <http://www.gnu.org/licenses>.
 *
 * Contact info:
 *
 *	Erivaldo Xavier de Lima Filho, desadoc@gmail.com
 *
 */

#include "SDL/GraphicDevice.hpp"
#include "SDL/Sprite.hpp"

#include "SDL/SDL.h"
#include "SDL/SDL_image.h"

#ifndef _NO_NAMESPACE
namespace lib2Desa {
#endif

namespace SDL {

class GraphicDeviceIn
{

public:
	SDL_Surface* screen;
	Uint32 clearColor;
};

void GraphicDevice::deInit(void)
{
	SDL_FreeSurface(in->screen);
	SDL_Quit();
}

GraphicDevice::GraphicDevice(void)
{
	in = new GraphicDeviceIn;
	in->screen = 0;
	in->clearColor = 0;
	//translation = vector<2,float>(0,0);
}

GraphicDevice::~GraphicDevice(void)
{
	deInit();
	delete in;
}

bool GraphicDevice::initScreen(u16 width, u16 height)
{
	if(in->screen) return false;

	if(SDL_Init(SDL_INIT_VIDEO) < 0){
		fprintf(stderr, "Could not initialize SDL.\n");
		return false;
	}

	in->screen = SDL_SetVideoMode(width, height, 24, SDL_SWSURFACE|SDL_DOUBLEBUF);

	if(!in->screen)
	{
		fprintf(stderr, "Could not initialize the window.\n");
		return false;
	}

	in->clearColor = SDL_MapRGB(in->screen->format, clearColor.get_r(), clearColor.get_g(), clearColor.get_b());

	return (in->screen != 0);
}

void GraphicDevice::refreshScreen(void)
{
	SDL_Flip(in->screen);
}

void GraphicDevice::setClearColor(Color c)
{
	clearColor = c;
	in->clearColor = SDL_MapRGB(in->screen->format, clearColor.get_r(), clearColor.get_g(), clearColor.get_b());
}

void GraphicDevice::clearScreen(void)
{
	if(!in->screen) return;

	SDL_FillRect(in->screen, NULL, in->clearColor);
}

shared_ptr<ISprite> GraphicDevice::load(const char* filename) const
{
	shared_ptr<ISprite> gs;

	gs = new Sprite;

	if(gs->load(filename)) return gs;
	else
	{
		//delete gs;
		return shared_ptr<ISprite>();
	}
}

void GraphicDevice::drawSprite(const shared_ptr<ISprite>& s, const vector2f& pos) const
{
	SDL_Surface* sf = (SDL_Surface*) s->getImageData();
	SDL_Rect area, dest;

	if(!sf) return;

	area.x = 0;
	area.y = 0;
	area.w = s->getSize().get_x();
	area.h = s->getSize().get_y();

	dest.x = (Sint16) pos.get_x();
	dest.y = (Sint16) pos.get_y();
	dest.w = ((Sint16) pos.get_x()) + s->getSize().get_x();
	dest.h = ((Sint16) pos.get_y()) + s->getSize().get_y();

	SDL_BlitSurface(sf,&area,in->screen,&dest);
}

}

#ifndef _NO_NAMESPACE
}
#endif
